package com.urbanski.clipboard.client.threads;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.client.ServerConnection;
import com.urbanski.util.logging.LoggingUtil;

public class ClipboardListener implements ClipboardOwner, Runnable
{
	private static final Logger LOGGER = Logger.getLogger(ClipboardListener.class);
	private static boolean instanceRunning = false;

	private Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
	private Object lock = new Object();
	private boolean started = false;
	
	@Override
	public void run()
	{
		LOGGER.trace("Entering ClipboardListener.run");

		synchronized (lock)
		{
			if (instanceRunning)
			{
				LOGGER.error("A clipboard listener is already running");
				return;
			}

			instanceRunning = true;
		}

		synchronized (lock)
		{
			LOGGER.info("Clipboard listener started");
			started = true;

			Transferable trans = clipboard.getContents(this);
			regainOwnership(trans);
			// processContents(trans);

			try
			{
				lock.wait();
			}
			catch (InterruptedException e)
			{

			}
		}

		synchronized (lock)
		{
			instanceRunning = false;

			LOGGER.info("Clipboard listener stopped");
			LOGGER.trace("Exiting ClipboardListener.run");
		}
	}

	public void stop()
	{
		synchronized (lock)
		{
			if (!started)
				return;
			LOGGER.info("Stopping clipboard listener");
			lock.notify();
		}
	}

	public void lostOwnership(Clipboard c, Transferable t)
	{
		try
		{
			Thread.sleep(100);
		}
		catch (InterruptedException e)
		{

		}
		Transferable contents = clipboard.getContents(this);
		processContents(contents);
		regainOwnership(contents);
	}

	private void processContents(Transferable t)
	{
		// DataFlavor dfToTest = null;

		if (t.isDataFlavorSupported(DataFlavor.stringFlavor))
		{
			try
			{
				String contents = (String)t.getTransferData(DataFlavor.stringFlavor);
				System.out.println(contents);
//				if (serverConnection != null)
//				{
//					serverConnection.sendData(contents);
//				}
			}
			catch (UnsupportedFlavorException | IOException e)
			{
				LoggingUtil.logAndPrintError(LOGGER, "Cannot represent clipboard contents as a String", e);
			}
		}
		// DataFlavor[] arr = t.getTransferDataFlavors();
		// for (DataFlavor df : arr)
		// {
		// System.out.println(df.getMimeType() + "///" + df.getRepresentationClass());
		// if
		// (df.getMimeType().equals("application/x-java-serialized-object; class=java.lang.String"))
		// dfToTest = df;
		// }
		// try
		// {
		// System.out.println(t.getTransferData(DataFlavor.stringFlavor));
		// }
		// catch (UnsupportedFlavorException e)
		// {
		// System.out.println("String not supported");
		// }
		//
		// try
		// {
		// System.out.println(t.getTransferData(DataFlavor.imageFlavor));
		// }
		// catch (UnsupportedFlavorException e)
		// {
		// System.out.println("Image not supported");
		// }
		//
		// if (dfToTest != null)
		// {
		// try
		// {
		// System.out.println("DF to test: " + dfToTest);
		// System.out.println(t.getTransferData(dfToTest));
		// }
		// catch (UnsupportedFlavorException e)
		// {
		// System.out.println("DF not supported");
		// }
		// }

		// try
		// {
		// System.out.println(t.getTransferData(DataFlavor.));
		// }
		// catch (UnsupportedFlavorException e)
		// {
		// System.out.println("String not supported");
		// }

		// Global.main.add(t);
	}

	void regainOwnership(Transferable t)
	{
		clipboard.setContents(t, this);
	}
}
